package com.hh.tc.ui.todo.addItem

import android.content.Context
import android.view.LayoutInflater
import androidx.appcompat.app.AlertDialog
import com.hh.base.util.ext.DateType
import com.hh.base.util.ext.toShow
import com.hh.base.util.ui.ToastUtil
import com.hh.db.core.ObjectBoxUtil
import com.hh.db.core.ObjectBoxUtil.queryFirst
import com.hh.db.core.ObjectBoxUtil.queryList
import com.hh.db.entity.TODODetail
import com.hh.db.entity.TODODetail_
import com.hh.db.entity.TODOItem
import com.hh.db.entity.TODOItem_
import com.hh.tc.databinding.AddItemDialogBinding
import java.util.Date

/**
 * 此文件为系统自动生成可自行编辑，依赖基础库参考 https://gitee.com/allen056/android_base_library
 * @author hHui
 * @Description: 增加item
 * @date 2025/04/16 10:00:36
 */
class AddItemDialog(private val context: Context) {
    private val viewBinding: AddItemDialogBinding
    private val builder = AlertDialog.Builder(context)
    private var dialog: AlertDialog

    init {
        AddItemDialogBinding.inflate(LayoutInflater.from(context)).apply {
            viewBinding = this
        }
        builder.setView(viewBinding.root)
        dialog = builder.create()
        dialog.requestWindowFeature(android.view.Window.FEATURE_NO_TITLE)
        dialog.setCancelable(true)
        dialog.window?.setBackgroundDrawableResource(android.R.color.transparent)

        viewBinding.yesNo.btnNeg.setOnClickListener {
            dismiss()
        }

    }

    fun show(todoItem: TODOItem? = null, listener: OnItemListener? = null) {
        viewBinding.apply {
            if (todoItem != null) {
                editItemName.setText(todoItem.name)
                editItemCount.setText(todoItem.timesPerDay.toString())
                editItemRemark.setText(todoItem.remark)
            } else {
                editItemName.setText("")
                editItemCount.setText("")
                editItemRemark.setText("")
            }
        }
        viewBinding.yesNo.btnPos.setOnClickListener {
            saveTodoItem(todoItem, listener)
        }
        dialog.show()
    }

    fun dismiss() {
        if (dialog.isShowing) {
            dialog.dismiss()
        }
    }

    private fun saveTodoItem(todoItem: TODOItem? = null, listener: OnItemListener? = null) {
        val name = viewBinding.editItemName.text.toString()
        if (name.isEmpty()) {
            ToastUtil.showToast(context, "请输入名称")
            return
        }
        val count = viewBinding.editItemCount.text.toString()
        if (count.isEmpty()) {
            ToastUtil.showToast(context, "请输入次数")
            return
        }
        if (todoItem == null) {
            ObjectBoxUtil.todoItemBox.queryFirst(TODOItem_.name.equal(name)).apply {
                if (this != null && this.name == name) {
                    ToastUtil.showToast(context, "名称已存在")
                    listener?.onError("名称已存在")
                    dismiss()
                    return
                }
            }
        }
        val result = todoItem.let {
            val newItem = TODOItem()
            if (it != null) {
                newItem.id = it.id
            }
            newItem.name = name
            newItem.timesPerDay = count.toInt()
            newItem.remark = viewBinding.editItemRemark.text.toString()
            newItem
        }
        ObjectBoxUtil.todoItemBox.put(result).apply {
            // 新增的--->创建今日的代办
            if (todoItem == null) {
                val list = ArrayList<TODODetail>()
                if (result.timesPerDay > 1) {
                    for (i in 0 until result.timesPerDay) {
                        val detail = TODODetail()
                        detail.toExecuteDay = Date().toShow(DateType.DAY)
                        detail.itemId = this
                        detail.item = result
                        detail.sort = i + 1
                        detail.itemName = "${result.name}(第${i + 1}次)"
                        list.add(detail)
                    }
                } else {
                    val detail = TODODetail()
                    detail.toExecuteDay = Date().toShow(DateType.DAY)
                    detail.item = result
                    detail.itemId = this
                    detail.itemName = result.name
                    list.add(detail)
                }
                ObjectBoxUtil.todoDetailBox.put(list)
                ToastUtil.showToast(context, "添加成功")
                listener?.onSuccess()
            } else {// 编辑
                //每日执行次数未变
                if (result.timesPerDay == todoItem.timesPerDay) {
                    ObjectBoxUtil.todoDetailBox.queryList(TODODetail_.itemId.equal(todoItem.id)).apply {
                        this.forEach {
                            it.item = result
                            if (result.timesPerDay == 1) {
                                it.itemName = result.name
                            } else {
                                it.itemName = "${result.name}(第${it.sort}次)"
                            }
                        }
                        ObjectBoxUtil.todoDetailBox.put(this)
                    }
                } else if (result.timesPerDay > todoItem.timesPerDay) {//每日执行次数增加了
                    //新增执行
                    val list = ArrayList<TODODetail>()
                    for (i in 0 until result.timesPerDay - todoItem.timesPerDay) {
                        val detail = TODODetail()
                        detail.toExecuteDay = Date().toShow(DateType.DAY)
                        detail.itemId = result.id
                        detail.item = result
                        detail.sort = i + 1 + todoItem.timesPerDay
                        detail.itemName = "${result.name}(第${i + 1 + todoItem.timesPerDay}次)"
                        list.add(detail)
                    }
                    ObjectBoxUtil.todoDetailBox.put(list)
                    //更新老的执行
                    ObjectBoxUtil.todoDetailBox.queryList(TODODetail_.itemId.equal(todoItem.id)).apply {
                        this.forEach {
                            it.item = result
                            it.itemName = "${result.name}(第${it.sort}次)"
                        }
                        ObjectBoxUtil.todoDetailBox.put(this)
                    }
                } else {//每日执行次数减少了
                    //删除多余的执行
                    ObjectBoxUtil.todoDetailBox.queryList(TODODetail_.itemId.equal(todoItem.id)).apply {
                        this.forEach {
                            if (it.sort > result.timesPerDay) {
                                ObjectBoxUtil.todoDetailBox.remove(it)
                            }
                        }
                    }
                    //更新老的执行
                    ObjectBoxUtil.todoDetailBox.queryList(TODODetail_.itemId.equal(todoItem.id)).apply {
                        this.forEach {
                            it.item = result
                            it.itemName = "${result.name}(第${it.sort}次)"
                        }
                        ObjectBoxUtil.todoDetailBox.put(this)
                    }
                }
                ToastUtil.showToast(context, "编辑成功")
                listener?.onSuccess()
            }
            dismiss()
        }
    }

    interface OnItemListener {
        fun onError(message: String)
        fun onSuccess()
    }
}
